import axios from 'axios'
import {getApi} from '@/main.js'
import {
	Notification,
	MessageBox,
	Message
} from 'element-ui'

//axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	baseURL: process.env.VUE_APP_BASE_API,
	// 超时
	timeout: 10000
})
// request拦截器
service.interceptors.request.use(config => {
	//config.url = getApi(config.url);
	config.url = config.url.replace(/^\/+/g, '')
	// 是否需要设置 token
	// get请求映射params参数
	if (config.method === 'get' && config.params) {
		let url = config.url + '?';
		for (const propName of Object.keys(config.params)) {
			const value = config.params[propName];
			var part = encodeURIComponent(propName) + "=";
			if (value !== null && typeof(value) !== "undefined") {
				if (typeof value === 'object') {
					for (const key of Object.keys(value)) {
						let params = propName + '[' + key + ']';
						var subPart = encodeURIComponent(params) + "=";
						url += subPart + encodeURIComponent(value[key]) + "&";
					}
				} else {
					url += part + encodeURIComponent(value) + "&";
				}
			}
		}
		url = url.slice(0, -1);
		config.params = {};
		config.url = url;
	}
	// 发送请求之前做某件事
	if (config.method === 'post') {
		//config.headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8";
	}
	return config
}, error => {
	console.log(error)
	Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
		const res = response.data
		console.log(res);
		// 响应码0为成功
		if (res.status !== 0) {
			if(res.status === 500){
				if(res.code === 500){
					Message.error({message:res.message,duration:3000});
				}
			}
		    return Promise.reject(new Error(res.message || 'Error'))
		} else {
		    return res
		}
	},
	error => {
		console.log('err' + error)
	}
)

export default service
